package network;

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class UdpEchoClient {
    //回显客户端
    private DatagramSocket socket = null;
    private String ip;
    private int servePort;
    public UdpEchoClient(String serveIp, int servePort ) throws SocketException {
        socket = new DatagramSocket();//首先创建socket对象
        //服务器一定要手动指定端口,客户端一般不要指定端口,系统自动分配
        //服务端比作餐厅,尽量不改变,而客户端相当于同学,坐在哪个餐桌无所谓
        this.servePort = servePort;
        this.ip = serveIp;
    }
    public void start() throws IOException {
        System.out.println("客户端启动");
        Scanner sc = new Scanner(System.in);

        while (true){
            //要做四个事情
            System.out.print("->");
            //1.控制台读取要发送的请求
            if(!sc.hasNextLine()){
                break;
            }
            String request = sc.next();
            //2.构造一个请求并发送
            //ip传入到数据报中不能用字符串
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(StandardCharsets.UTF_8),request.getBytes().length
            , InetAddress.getByName(ip), servePort);
            socket.send(requestPacket);
            //3.读取服务器的响应
            DatagramPacket  responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            //4.把响应显示到控制台上
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1",9090);
        udpEchoClient.start();
    }
}
